<template>
  <div ref="chartEl" style="height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { defineProps } from 'vue';

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({
      categories: [],
      values: []
    })
  }
})

const chartEl = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartEl.value) return
  
  chartInstance = echarts.init(chartEl.value)
  updateChart()
  
  // 响应窗口变化
  const resizeHandler = () => chartInstance.resize()
  window.addEventListener('resize', resizeHandler)
  onBeforeUnmount(() => window.removeEventListener('resize', resizeHandler))
}

const updateChart = () => {
  if (!chartInstance) return

  // 定义每个类型的柱子颜色
  const colors = [
    '#FF0084', // 音乐
    '#0000FF', // 科技
    '#00CE56', // 股市
    '#812CB0', // 政策
    '#9966FF', // 游戏
    '#FF9F40', // 运动
    '#FF6384', // 学术
    '#36A2EB', // 军事
    '#FFCE56', // 娱乐
    '#4BC0C0'  // 影视
  ]

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
  
    xAxis: {
      type: 'category',
      data: props.data.categories,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [{
      data: props.data.values.map((value, index) => ({
        value,
        itemStyle: {
          color: colors[index]
        }
      })),
      type: 'bar',
      barWidth: '60%'
    }],
    grid: {
      containLabel: true,
      left: '4%', // 调整网格左侧留白以容纳文字
      right: '3%',
      bottom: '10%'
    },
    graphic: [
      {
        type: 'text',
        left: '5%', // 文字位置调整到左上方
        top: '5%', // 文字位置调整到左上方
        style: {
          text: '事件类型分布', // 新增文字
          textAlign: 'left',
          fontSize: 20,
          fontWeight: 'bold',
          fill: '#333'
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(initChart)
watch(() => props.data, updateChart, { deep: true })
</script>